package com.dq.jingran.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dq.jingran.entity.JrSpace;
import com.dq.jingran.entity.JrUser;
import com.dq.jingran.exception.ExceptionVo;
import com.dq.jingran.service.JrCommentsService;
import com.dq.jingran.service.JrSpaceService;
import com.dq.jingran.mapper.JrSpaceMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dq.jingran.service.JrUserService;
import com.dq.jingran.utils.UserPropertiesUtils;
import com.dq.jingran.vo.space.SpaceAndCommendsVo;
import com.dq.jingran.vo.space.SpaceCommentsVo;
import com.dq.jingran.vo.space.SpaceUserVo;
import com.dq.jingran.vo.space.SpaceVo;
import com.dq.jingran.vo.space.upfile.UpSpace;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * (JrSpace)表服务实现类
 *
 * @author Dq
 * @since 2022-09-24 15:51:47
 */
@Service
public class JrSpaceServiceImpl extends ServiceImpl<JrSpaceMapper, JrSpace> implements JrSpaceService {
    @Autowired
    private JrSpaceMapper spaceMapper;

    @Autowired
    private JrCommentsService commentsService;

    @Autowired
    private JrUserService userService;

    @Resource
    private UserPropertiesUtils userPropertiesUtils;

    //获取所有空间和评论
    @Override
    public List<SpaceAndCommendsVo> getAllInfoAndCommend() {
        /**
         * 1. 获取父类的id
         * 2. 然后根据父类的if 循环获取子类评论 并且封装
         * 3. 最后VO对象封装
         */
        LambdaQueryWrapper<JrSpace> jrSpaceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        jrSpaceLambdaQueryWrapper.orderByDesc(JrSpace::getGmtTime);
        List<JrSpace> jrSpaces = spaceMapper.selectList(jrSpaceLambdaQueryWrapper);
        ArrayList<SpaceAndCommendsVo> spaceAndCommendsVos = new ArrayList<>();
        for (JrSpace jrSpace : jrSpaces) {
            /**
             * 1. 把jrSpace 封装为SpaceVo
             * 2. 封装CommendListVo对象
             */
            SpaceAndCommendsVo spaceAndCommendsVo = new SpaceAndCommendsVo();
            SpaceVo spaceVo = copy(jrSpace);
            String userId = jrSpace.getUserId();  //用于查找用户的id
            SpaceUserVo user = userService.getSomeInfoToSpace(userId);

            String id = jrSpace.getId(); //用于查找评论的id
            List<SpaceCommentsVo> commentsList=commentsService.findAllDataBySpaceId(id);
            List<SpaceUserVo> likes=commentsService.findAllLike(id);

            spaceVo.setUser(user);
            spaceAndCommendsVo.setSpace(spaceVo);
            spaceAndCommendsVo.setCommentsList(commentsList);
            spaceAndCommendsVo.setLike(likes);
            spaceAndCommendsVos.add(spaceAndCommendsVo);
        }
        return spaceAndCommendsVos;
    }

    //上传空间文件
    @Override
    public void upSpace(MultipartFile file, String userId,String reviews) {
        try {
            COSClient cosClient = getCosClient();
            /**
             * 1. 获取流
             * 2. 拼接name  uuid 。jpg
             * 3. 设置size 节约空间
             * 4. 设置请求体
             * 5. 发送最终上传指令
             */

            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            String pic = UUID.randomUUID().toString().replace("-", ""); //UUID
            String picName = file.getOriginalFilename(); //文件名称 用于获取后缀名
            String nowDate = new DateTime().toString("yyyy/MM/dd");
            assert picName != null;
            // 1. /space/   2. 2022/7/20  3. /  4. 011619125c53add6%21400x400  5. .jpg
            String picUrlNameAndType = "/space/"+nowDate +"/"+ pic + picName.substring(picName.lastIndexOf("."));
            //设置流的大小
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(file.getSize());
            //设置对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(userPropertiesUtils.getBucketName(), picUrlNameAndType, inputStream, objectMetadata);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            //关闭
            cosClient.shutdown();

            //统一返回 此路径规则：https://guli-dq-1310347558.cos.ap-chengdu.myqcloud.com/guli/011619125c53add6%21400x400.jpg
            String ResultUrl = userPropertiesUtils.getUrl() + picUrlNameAndType;

            JrSpace jrSpace = new JrSpace();
            jrSpace.setImg(ResultUrl);
            jrSpace.setUserId(userId);
            jrSpace.setReviews(reviews);
            spaceMapper.insert(jrSpace);

        } catch (Exception e) {
            throw new ExceptionVo(401,"OSS Error");
        }
    }


    /**
     * 初始化CosClient相关配置， appid、accessKey、secretKey、region
     *
     * @return
     */
    public COSClient getCosClient() {
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(userPropertiesUtils.getSecretId(), userPropertiesUtils.getSecretKey());
        ClientConfig clientConfig = new ClientConfig(new Region(userPropertiesUtils.getRegion()));
        // 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }


    public SpaceVo copy(JrSpace jrSpace){
        SpaceVo spaceVo = new SpaceVo();
        BeanUtils.copyProperties(jrSpace,spaceVo);
        return spaceVo;
    }
}